<template>
  <view class="address-edit">
    <view class="header">
      <text class="title">{{isEdit? '编辑地址' : '新增地址'}}</text>
    </view>

    <view class="form-container">
      <view class="form-item">
        <text class="label">收货人</text>
        <input 
          type="text"
          v-model="formData.name"
          placeholder="请输入收货人姓名"
          class="input"
        />
      </view>

      <view class="form-item">
        <text class="label">手机号码</text>
        <input 
          type="text" 
          v-model="formData.phone"
          placeholder="请输入手机号码"
          maxlength="11"
          class="input"
        />
      </view>

      <view class="form-item">
        <text class="label">所在城市</text>
        <!-- 更规范的下拉框样式 -->
        <view class="city-select-container">
          <picker mode="selector" :range="cityList" @change="onCityChange" :value="cityIndex">
            <view class="city-select">
              <text class="city-text">{{formData.city}}</text>
              <view class="select-arrow"></view>
            </view>
          </picker>
        </view>
      </view>

      <view class="form-item">
        <text class="label">小区/大厦</text>
        <input 
          type="text"
          v-model="formData.department"
          placeholder="请输入小区/大厦名称"
          class="input"
        />
      </view>

      <view class="form-item">
        <text class="label">楼号/门牌</text>
        <input 
          type="text"
          v-model="formData.houseNumber"
          placeholder="请输入详细楼号/门牌号"
          class="input"
        />
      </view>

      <view class="form-item switch-item">
        <text class="label">设为默认地址</text>
        <switch 
          :checked="formData.isDefault"
          @change="handleDefaultChange"
          color="#1b76f6"
        />
      </view>
    </view>

    <view class="footer">
      <button class="save-btn" @click="handleSave">保存</button>
    </view>
  </view>
</template>

<script>
	import Config from '@/Config.js'
export default {
  data() {
    return {
      isEdit: false,
      userId: '',
      formData: {
        id: '',
        name: '',
        phone: '',
        city: '',
        department: '',
        houseNumber: '',
        isDefault: false
      },
      cityList: [
        '北京', '上海', '洛阳', '天津', '成都', '杭州', '武汉', '西安',
        '南京', '重庆',  '苏州', '长沙', '郑州', '徐州', '青岛',
        '宁波', '昆明', '大连', '厦门', '合肥', '佛山', '福州', '哈尔滨',
        '济南', '南昌', '长春', '太原', '贵阳', '石家庄', '泉州','新疆','西藏',
        '南宁', '海口', '呼和浩特', '乌鲁木齐', '兰州', '西宁', '银川', '拉萨'
      ],
      cityIndex: 0
    }
  },

  onLoad(options) {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      this.userId = JSON.parse(userInfo)._id
    }

    if (options.address) {
      this.isEdit = true
      const address = JSON.parse(decodeURIComponent(options.address))
      this.formData = { ...address }
      this.cityIndex = this.cityList.indexOf(this.formData.city) >= 0 ? this.cityList.indexOf(this.formData.city) : 0;
    }
  },

  methods: {
    handleDefaultChange(e) {
      this.formData.isDefault = e.detail.value
    },

    validateForm() {
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        })
        return false
      }

      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({
          title: '手机号码格式不正确',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.city) {
        uni.showToast({
          title: '请输入或选择所在城市',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.department) {
        uni.showToast({
          title: '请输入小区/大厦名称',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.houseNumber) {
        uni.showToast({
          title: '请输入楼号/门牌号',
          icon: 'none'
        })
        return false
      }

      return true
    },

    onCityChange(e) {
      this.cityIndex = e.detail.value;
      this.formData.city = this.cityList[this.cityIndex];
    },

    async handleSave() {
      if (!this.validateForm()) return

      try {
        const getUserResponse = await uni.request({
          url: Config.api_host+'/users',
          method: 'GET'
        })

        if (getUserResponse.statusCode !== 200) {
          throw new Error('获取用户数据失败')
        }

        const users = getUserResponse.data
        const currentUser = users.find(user => user.id === this.userId)

        if (!currentUser) {
          throw new Error('用户不存在')
        }

        let addresses = currentUser.addresses || []
        const now = new Date().toISOString()

        if (!this.isEdit && addresses.length === 0) {
          this.formData.isDefault = true
        }

        if (this.formData.isDefault) {
          addresses = addresses.map(addr => ({
            ...addr,
            isDefault: false
          }))
        }

        if (this.isEdit) {
          addresses = addresses.map(addr => 
            addr.id === this.formData.id 
              ? { ...this.formData, updatedAt: now }
              : addr
          )
        } else {
          const newAddress = {
            ...this.formData,
            id: Date.now().toString(),
            createdAt: now,
            updatedAt: now
          }
          addresses.push(newAddress)
        }

        const updateResponse = await uni.request({
          url:Config.api_host+`/users/${this.userId}`,
          method: 'PUT',
          data: {
            ...currentUser,
            addresses
          }
        })

        if (updateResponse.statusCode === 200) {
          uni.showToast({
            title: this.isEdit? '修改成功' : '添加成功',
            icon: 'success'
          })

          setTimeout(() => {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            if (prevPage && prevPage.$vm.fetchAddresses) {
              prevPage.$vm.fetchAddresses()
            }
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error('保存失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '保存失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss">
.address-edit {
  min-height: 100vh;
  background-color: #f5f5f5;

  .header {
    background-color: #fff;
    padding: 30rpx;
    border-bottom: 1px solid #eee;

    .title {
      font-size: 32rpx;
      font-weight: 500;
    }
  }

  .form-container {
    margin-top: 20rpx;
    background-color: #fff;
    padding: 0 30rpx;

    .form-item {
      display: flex;
      align-items: center;
      padding: 30rpx 0;
      border-bottom: 1px solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .label {
        width: 180rpx;
        font-size: 28rpx;
        color: #333;
      }

      .input {
        flex: 1;
        font-size: 28rpx;
      }

      &.switch-item {
        justify-content: space-between;
      }
    }

   .city-select-container {
      flex: 1;
      position: relative;
      border: 1px solid #d1d5db;
      border-radius: 6px;
      overflow: hidden;
      margin-left: 10px;
    }

   .city-select {
      display: flex;
      align-items: center;
      padding: 10px 12px;
      cursor: pointer;
    }

   .city-text {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }

   .select-arrow {
      width: 0;
      height: 0;
      border-left: 8rpx solid transparent;
      border-right: 8rpx solid transparent;
      border-top: 8rpx solid #999;
      margin-left: 10rpx;
    }
  }

  .footer {
    padding: 40rpx 30rpx;

    .save-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #1b76f6;
      color: #fff;
      font-size: 32rpx;
      border-radius: 10rpx;

      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style>